<template>
	<view class="container">
		<canvas type="webgl" class="webgl" id="gl" canvas-id="gl" @touchstart="handleTouch" @touchmove="handleTouch" @touchend="handleTouch"></canvas>
	</view>
</template>

<script>
	import * as THREE from 'three-platformize'
	import {
		OrbitControls
	} from 'three-platformize/examples/jsm/controls/OrbitControls'
	import {
		WechatPlatform
	} from 'three-platformize/src/WechatPlatform'
	export default {
		data() {
			return {
				disposing: false,
				platform: null,
				camera: null,
				scene: null,
				renderer: null,
				cube: null,
				controls: null,
				frameId: null
			};
		},
		onReady() {
			uni.createSelectorQuery().in(this).select('#gl').node().exec((res) => {
				if (!res || !res[0]) {
					console.error('未找到 canvas 元素，请检查 id');
					return;
				}
				const canvas = res[0].node;
				if (!canvas) {
					console.error('canvas 元素为空');
					return;
				}
				// 初始化平台
				this.platform = new WechatPlatform(canvas);
				THREE.PLATFORM.set(this.platform);
				//初始化相机
				this.camera = new THREE.PerspectiveCamera(
					75,
					canvas.width / canvas.height,
					0.1,
					1000);
				//初始化场景
				this.scene = new THREE.Scene();
				//初始化渲染器
				this.renderer = new THREE.WebGL1Renderer({
					canvas,
					antialias: true,
					alpha: true
				});
				this.renderer.setSize(canvas.width, canvas.height);
				this.renderer.setPixelRatio(THREE.$window.devicePixelRatio);
				// 创建立方体
				const geometry = new THREE.BoxGeometry(1, 1, 1);
				const material = new THREE.MeshBasicMaterial({
					color: 0x00ff00
				});
				this.cube = new THREE.Mesh(geometry, material);
				this.scene.add(this.cube);
				// 设置相机位置
				this.camera.position.z = 5;
				// 坐标轴
				const createAxes = () => {
					const axesHelper = new THREE.AxesHelper(6);
					this.scene.add(axesHelper);
				};
				// 轨道控制器
				const createOrbit = () => {
					this.controls = new OrbitControls(this.camera, canvas);
					this.controls.enableDamping = true; // 添加阻尼效果
					this.controls.dampingFactor = 0.1;
				};
				// 渲染函数
				const animate = () => {
					if (!this.disposing) {
						this.frameId = THREE.$requestAnimationFrame(animate);
					}
					this.controls.update(); // 阻尼效果需要更新
					this.renderer.render(this.scene, this.camera);
				};

				createAxes();
				createOrbit();
				animate();
			})
		},
		onUnload() {
			this.disposing = true;
			THREE.$cancelAnimationFrame(this.frameId);
			THREE.PLATFORM.dispose();

			// 清理资源
			if (this.renderer) {
				this.renderer.dispose();
			}
			if (this.scene) {
				this.scene.clear();
			}
			if (this.controls) {
				this.controls.dispose();
			}
		},
		methods: {
			handleTouch(e) {
				this.platform?.dispatchTouchEvent(
				e); //如果 this.platform 存在，就调用它的 dispatchTouchEvent 方法并传入 e；如果 this.platform 不存在，就什么都不做，也不报错。
			}
		}
	}
</script>

<style>

</style>